﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class CameraSelectionGrid : MonoBehaviour
{
    private Vector3 GridStartPoint;
    private Vector3 GridEndPoint;

    private List<GameObject> SelectedUnits = new List<GameObject>();

    // Update is called once per frame
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
            GridStartPoint = Input.mousePosition;

        if (Input.GetMouseButtonUp(0))
        {
            GridEndPoint = Input.mousePosition;

            if (GridEndPoint.x < GridStartPoint.x)
            {
                float x = GridStartPoint.x; GridStartPoint.x = GridEndPoint.x; GridEndPoint.x = x;
            } 
            if (GridEndPoint.y > GridStartPoint.y)
            {
                float y = GridStartPoint.y; GridStartPoint.y = GridEndPoint.y; GridEndPoint.y = y;
            }

            Camera cam = Camera.main;
            SelectedUnits.Clear();
            foreach (GameObject go in GameObject.FindGameObjectsWithTag("Unit_Basic"))
            {
                Vector3 screenPos = cam.WorldToScreenPoint(go.transform.position);
                if (screenPos.x > GridStartPoint.x && screenPos.x < GridEndPoint.x &&
                    screenPos.y < GridStartPoint.y && screenPos.y > GridEndPoint.y)
                    SelectedUnits.Add(go);
                Debug.Log(screenPos);
                Debug.Log(GridStartPoint);
                Debug.Log(GridEndPoint);
            }
            Debug.Log(SelectedUnits.Count);
        }

    }

    void OnGUI()
    {
        if (Input.GetMouseButton(0))
        {
            GridEndPoint = Input.mousePosition;

            GUI.Box(new Rect(GridStartPoint.x, Screen.height - GridStartPoint.y, GridEndPoint.x - GridStartPoint.x, GridStartPoint.y - GridEndPoint.y), "");
        }

        //GUILayout.BeginHorizontal();
        foreach (GameObject go in SelectedUnits)
        {
            GUILayout.Button(go.name);
        }
        //GUILayout.EndHorizontal();
    }
}
